package com.cn.controller;

import java.io.File;
import java.io.IOException;
import java.security.Permission;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cn.common.basecon.BaseController;
import com.cn.model.User;
import com.cn.service.IUserService;

import utils.MD5Util;

@Controller  
public class UserController extends BaseController {  
    private static Logger log=LoggerFactory.getLogger(UserController.class);
     @Resource 
     private IUserService userService;    
    
     /**
 	 * 初始登陆界面
 	 * @param request
 	 * @return
 	 */
 	@RequestMapping(value="/login.do",method=RequestMethod.GET)
 	public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){
 		log.debug("来自IP[" + request.getRemoteHost() + "]的访问");
 		return "login";
 	}
     //用户登录
     @RequestMapping(value="/checkLogin.do",method=RequestMethod.POST )
     @ResponseBody
     public String login(User user, HttpServletRequest request,HttpServletResponse response) throws Exception {
    	 Subject subject = SecurityUtils.getSubject();
         UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), MD5Util.md5Encode(user.getPassword()));
        /* Cookie[] cookies = request.getCookies();
         if (cookies!=null) {
              log.info("您上次访问的时间是：");
              for (int i = 0; i < cookies.length; i++) {
                  	  Cookie cookie = cookies[i];
                  if (cookie.getName().equals("lastAccessTime")) {
                      Long lastAccessTime =Long.parseLong(cookie.getValue());
                      Date date = new Date(lastAccessTime);
                      log.info(lastAccessTime.toString()+date.toString());
                 }else{
                	 Cookie cookie1 = new Cookie("lastAccessTime", System.currentTimeMillis()+"");//创建一个cookie，cookie的名字是lastAccessTime 
                	 log.info("创建cookie"+cookie1);
                	 cookie1.setMaxAge(24*60*60);
                	 response.addCookie(cookie1);
                 }
              }
          }else {
              log.info("这是您第一次访问本站！");
        }*/
         try{
        	 token.setRememberMe(true);
             subject.login(token);//会跳到我们自定义的realm中
             request.getSession().setAttribute("user", user);
             return "success";
         }catch(Exception e){
             e.printStackTrace();
             request.getSession().setAttribute("user", user);
             request.setAttribute("error", "用户名或密码错误！");
             return "login";
         }
     }

     @RequestMapping("/logout")
     public String logout(HttpServletRequest request) {
    	 Subject subject = SecurityUtils.getSubject();
    	 subject.logout();
         return "login";
     }   

     @RequestMapping("/admin")
     public String admin(HttpServletRequest request) {
         return "success";
     }

     @RequestMapping("/student")
     @RequiresPermissions("user:create")
     public String student(HttpServletRequest request) {
         return "success";
     }   

     @RequestMapping("/teacher")
     public String teacher(HttpServletRequest request) {
         return "success";
     }  
    @RequestMapping(value="/test",method=RequestMethod.GET)  
    public String test(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt(request.getParameter("id"));  
        System.out.println("userId:"+userId);
        User user=null;
        if (userId==1) {
             user = new User();  
             user.setAge(11);
             user.setId(1);
             user.setPassword("123");
             user.setUserName("javen");
        }
       
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return "index";  
    }  
    
    
    @RequestMapping(value="/showUser",method=RequestMethod.GET)  
    public String toIndex(HttpServletRequest request,Model model){  
        int userId = Integer.parseInt("1");  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        if(user!=null){
        	setSessionUser(request, user);
        }
        getSessionUser();
        log.debug(loginUser.getUserName());
        model.addAttribute("user", user);  
        return "User";  
    }  
    
    @RequestMapping(value="/showUser2",method=RequestMethod.GET)  
    public ModelMap toIndex2(@RequestParam("id") String id,Model model){  
    	ModelMap map = new ModelMap();
    	map.put("flag", true);
    	int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.addAttribute("user", user);  
        return map;  
    }  
    
    
    @RequestMapping(value="/showUser3/{id}",method=RequestMethod.GET)  
    public String toIndex3(@PathVariable("id")String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.debug(user.toString());
        model.put("user", user);  
        return "showUser";  
    }  
    
    @RequestMapping(value="/u/{id}",method=RequestMethod.GET)  
    public @ResponseBody User getUserInJson(@PathVariable String id,Map<String, Object> model){  
        User user = new User();
        log.info("---------------------");
        return user;  
    }  
    
    @RequestMapping(value="/jsontype/{id}",method=RequestMethod.GET)  
    public ResponseEntity<User>  getUserInJson2(@PathVariable String id,Map<String, Object> model){  
        int userId = Integer.parseInt(id);  
        System.out.println("userId:"+userId);
        User user = this.userService.getUserById(userId);  
        log.info(user.toString());
        return new ResponseEntity<User>(user,HttpStatus.OK);  
    } 
    
    //文件上传、
    @RequestMapping(value="/upload")
    public String showUploadPage(){
        return "user_admin/file";
    }
    
    @RequestMapping(value="/doUpload",method=RequestMethod.POST)
    public String doUploadFile(@RequestParam("file")MultipartFile file) throws IOException{
        if (!file.isEmpty()) {
            log.info("Process file:{}",file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:\\",System.currentTimeMillis()+file.getOriginalFilename()));
        return "succes";
    }
}  